package com.example.shiro.demo.redis;

/**
 * <Description> <br>
 *
 * @author renweiping<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/10/14 17:47 <br>
 * @see com.example.shiro.demo <br>
 */

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

@Component
public class RedisCache<K,V> implements Cache<K,V> {

    private static final Logger log = LoggerFactory.getLogger(RedisCache.class);


    @Resource
    RedisUtil redisUtil;

    private final String CACHE_PREFIX = "redis-cache";

    private byte[] getKey(K k){

        if (k==null || !StringUtils.hasText(k.toString())){
            return null;
        }

        if(k instanceof String && StringUtils.hasText(k.toString())){
            return (CACHE_PREFIX + k).getBytes();
        }
        return SerializationUtils.serialize(k);
    }

    @Override
    public V get(K key) throws CacheException {
        byte keyByte[] = getKey(key);

        if (keyByte == null){
            return null;
        }

        byte[] value = redisUtil.get(keyByte);
        if(value != null){
            return (V)SerializationUtils.deserialize(value);
        }
        return null;
    }

    @Override
    public V put(K k, V v) throws CacheException {
        byte[] key = getKey(k);
        byte[] value = SerializationUtils.serialize(v);
        redisUtil.set(key,value);
        redisUtil.expire(key,600);
        return v;
    }

    @Override
    public V remove(K k) throws CacheException {
        byte[] key =  getKey(k);
        byte[] value = redisUtil.get(key);
        redisUtil.del(key);
        if(value != null ){
            return (V)SerializationUtils.deserialize(value);
        }
        return null;
    }

    @Override
    public void clear() throws CacheException {

    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<K> keys() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }
}
